package com.ikingtech.framewor.rt.spring.boot.starter;

import com.ikingtech.framework.sdk.utils.Tools;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static com.ikingtech.framework.sdk.context.constant.CommonConstants.GLOBAL_CONFIG_PREFIX;
import static com.ikingtech.framework.sdk.context.constant.CommonConstants.SECURITY_FILTER_ORDER;

/**
 * @author tie yan
 */
public class RtAutoConfiguration {

    /**
     * Filter for modifying request path.
     */
    @Bean
    @ConditionalOnProperty(prefix = GLOBAL_CONFIG_PREFIX + ".web", name = "arch", havingValue = "single")
    public FilterRegistrationBean<RequestPathFilter> requestFilterRegister() {
        FilterRegistrationBean<RequestPathFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RequestPathFilter());
        registration.addUrlPatterns("/*");
        registration.setName("requestPathFilter");
        registration.setOrder(0);
        return registration;
    }

    /**
     * Configuration for CORS filter.
     * @return The CORS configuration object.
     */
    @Bean
    @ConditionalOnProperty(prefix = GLOBAL_CONFIG_PREFIX + ".web", name = "arch", havingValue = "single")
    public FilterRegistrationBean<CorsFilter> corsFilterRegister() {
        // 初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        // 给配置源对象设置过滤的参数
        // 参数一: 过滤的路径 == > 所有的路径都要求校验是否跨域
        // 参数二: 配置类
        configurationSource.registerCorsConfiguration("/**", corsFilterConfiguration());
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CorsFilter(configurationSource));
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(SECURITY_FILTER_ORDER - 2);
        return registration;
    }

    private CorsConfiguration corsFilterConfiguration(){
        // 初始化cors配置对象
        CorsConfiguration configuration = new CorsConfiguration();

        // 设置允许跨域的域名,如果允许携带cookie的话,路径就不能写*号, *表示所有的域名都可以跨域访问
        configuration.addAllowedOriginPattern("*");
        // 设置跨域访问可以携带cookie
        configuration.setAllowCredentials(true);
        // 允许所有的请求方法 ==> GET POST PUT Delete
        configuration.addAllowedMethod("*");
        // 允许携带任何头信息
        configuration.addAllowedHeader("*");
        return configuration;
    }

    public static class RequestPathFilter extends OncePerRequestFilter {

        @Override
        protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws IOException, ServletException {
            String originPath = request.getRequestURI();
            request.getRequestDispatcher(Tools.Str.removePrefix(originPath, "/server", "/auth")).forward(request, response);
        }
    }
}
